import 'package:flutter/material.dart';

class ScaleAnimation extends StatefulWidget {
  final Curve curve;

  final double beginScale;

  final double endScale;

  final double? beginOpacity;

  final Widget? child;

  final bool autoStart;

  final Duration? duration;

  final Duration? delayDuration;

  final Function(AnimationController controller)? onCreateController;

  const ScaleAnimation({
    super.key,
    this.curve = Curves.fastOutSlowIn,
    this.beginScale = 0.5,
    this.endScale = 1,
    this.beginOpacity,
    this.child,
    this.autoStart = true,
    this.duration = const Duration(milliseconds: 2000),
    this.delayDuration,
    this.onCreateController,
  });

  @override
  State<StatefulWidget> createState() {
    return _AlphaAnimationState();
  }
}

class _AlphaAnimationState extends State<ScaleAnimation>
    with TickerProviderStateMixin {
  late final AnimationController controller;

  late final Animation<double> scale;
  late final Animation<double> opacity;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: widget.duration,
      vsync: this,
    );
    scale = Tween(
      begin: widget.beginScale,
      end: widget.endScale,
    ).animate(
      CurvedAnimation(
        parent: controller,
        curve: Interval(
          0,
          1,
          curve: widget.curve,
        ),
      ),
    );
    opacity = Tween(
      begin: widget.beginOpacity ?? 1,
      end: 1.0,
    ).animate(
      CurvedAnimation(
        parent: controller,
        curve: Interval(
          0,
          1,
          curve: widget.curve,
        ),
      ),
    );
    if (widget.autoStart) {
      Future.delayed(widget.delayDuration ?? const Duration()).then((value) {
        controller.forward();
      });
    }
    widget.onCreateController?.call(controller);
  }

  @override
  dispose() {
    controller.stop();
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      builder: (BuildContext context, child) {
        return Transform.scale(
          scale: scale.value,
          child: Opacity(
            opacity: opacity.value,
            child: widget.child,
          ),
        );
      },
      animation: controller,
    );
  }
}
